import axios from 'axios'
import config from '@/utils/config'
import { Message } from 'view-design'

axios.interceptors.request.use((config) => {
  // 在发送请求之前做些什么
  return config
}, (error) => {
  // 对请求错误做些什么
  return Promise.reject(error)
})

axios.interceptors.response.use((response) => {
  console.log(response)
  if (response.data.code !== 200) {
    Message.error(response.data.msg)
  }
  return response
}, (error) => {
  // 对响应错误做点什么
  Message.error('Network Error')
  return Promise.reject(error)
})

export const serviceHandle = (method, path, param, headers) => {
  headers = headers || {}
  method = method.toUpperCase()
  path = config.api + path
  // 对地址前缀与其他接口不同的进行区别对待
  if (method === 'GET') {
    return new Promise((resolve, reject) => {
      axios.get(path, { params: param }, { headers: headers }).then((response) => {
        resolve(response.data)
      })
    })
  } else if (method === 'POST') {
    return new Promise((resolve, reject) => {
      axios.post(path, param, { headers: headers }).then((response) => {
        resolve(response.data)
      })
    })
  }
}
